﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// provides methods for working with pasword hash
/// </summary>
public static class PasswordHash
{
    /// <summary>
    /// get MD5 hash of a string
    /// </summary>
    /// <param name="input">string to be hashed</param>
    /// <returns>MD5 hash</returns>
    public static string GetMd5Hash(string input)
    {
        // create a new MD5CryptoServiceProvider to hash string
        System.Security.Cryptography.MD5CryptoServiceProvider md5Hash = new System.Security.Cryptography.MD5CryptoServiceProvider();

        // add salt to original string
        input += ApplicationGlobalVariables.Md5HashSalt;

        // convert the input string to a byte array and compute the hash
        byte[] data = md5Hash.ComputeHash(System.Text.Encoding.UTF8.GetBytes(input));

        // create a new Stringbuilder to collect the bytes and create a string
        System.Text.StringBuilder sBuilder = new System.Text.StringBuilder();

        // loop through each byte of the hashed data and format each one as a hexadecimal string
        for (int i = 0; i < data.Length; i++)
            sBuilder.Append(data[i].ToString("x2"));

        // return the hexadecimal string.
        return sBuilder.ToString();
    }

    /// <summary>
    /// Verify a hash against a string, oridinal and ignore-case string comparison used
    /// </summary>
    /// <param name="input">string to compare</param>
    /// <param name="hash">hash to compare</param>
    /// <returns>true if hash matches the string, otherwise false</returns>
    public static bool VerifyMd5Hash(string input, string hash)
    {
        // add salt to original string
        input += ApplicationGlobalVariables.Md5HashSalt;

        // hash the input
        string hashOfInput = GetMd5Hash(input);

        // create a StringComparer an compare the hashes
        StringComparer comparer = StringComparer.OrdinalIgnoreCase;

        // return if two string match
        return comparer.Compare(hashOfInput, hash) == 0;
    }
}